﻿// -----------------------------------------------------------------------
//  <copyright file="DaprPlusHubBase.cs" company="LiuliuSoft">
//      Copyright (c) 2025 66SOFT. All rights reserved.
//  </copyright>
//  <site>https://ifs.66soft.net</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-09-28 01:09</last-date>
// -----------------------------------------------------------------------

using Microsoft.AspNetCore.SignalR;


namespace DaprPlus.AspNetCore.SignalR;

internal static class InternalHubHelper
{
    public static async Task HandleConnectedAsync(IConnectionUserCache cache, HubCallerContext context, ILogger logger)
    {
        var userName = context.User?.Identity?.Name;
        if (!string.IsNullOrEmpty(userName))
        {
            await cache.AddConnectionId(userName, context.ConnectionId);
            logger.LogInformation("用户【{UserName}】连接到服务器，连接Id:{ConnectionId}", userName, context.ConnectionId);
        }
    }

    public static async Task HandleDisconnectedAsync(IConnectionUserCache cache, HubCallerContext context,
        ILogger logger, Exception? exception)
    {
        var userName = context.User?.Identity?.Name;
        if (!string.IsNullOrEmpty(userName))
        {
            await cache.RemoveConnectionId(userName, context.ConnectionId);
            logger.LogInformation("用户【{UserName}】从服务器断开，连接Id:{ConnectionId}", userName, context.ConnectionId);
        }

        if (exception != null)
        {
            logger.LogError(exception, "连接 {ConnectionId} 因异常断开。", context.ConnectionId);
        }
    }

    public static async Task HandleAddToGroup(IGroupManager groups, HubCallerContext context, ILogger logger,
        params string[] groupNames)
    {
        Check.NotNull(groupNames, nameof(groupNames));

        foreach (var groupName in groupNames)
        {
            await groups.AddToGroupAsync(context.ConnectionId, groupName);
            logger.LogInformation("连接{ConnectionId}加入组【{GroupName}】", context.ConnectionId, groupName);
        }
    }

    public static async Task HandleRemoveFromGroup(IGroupManager groups, HubCallerContext context, ILogger logger,
        string[] groupNames)
    {
        Check.NotNull(groupNames, nameof(groupNames));

        foreach (var groupName in groupNames)
        {
            await groups.RemoveFromGroupAsync(context.ConnectionId, groupName);
            logger.LogInformation("连接{ConnectionId}退出组【{GroupName}】", context.ConnectionId, groupName);
        }
    }
}